<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import type { PropType } from 'vue';
import { Play, Trash2, GripVertical } from '@vben/icons';
import { $t } from '@vben/locales';
import { generateUUID } from '#/utils/generateUUID';
import SetTextFormat from '#/components/setTextFormat.vue';
import draggable from 'vuedraggable';
import { UploadIcon } from './index';
defineOptions({ name: 'Query' });

interface ProcessNodeType {
  processNodeConfigs: {
    id: string;
    icon: string;
    mainTitle: string;
    mainTextFormatConfigs: {
      fontSize: number;
      fontColor: string;
      fontBold: boolean;
      italic: boolean;
      underline: boolean;
    };
    subTitle: string;
    subTextFormatConfigs: {
      fontSize: number;
      fontColor: string;
      fontBold: boolean;
      italic: boolean;
      underline: boolean;
    };
    isActive: boolean;
  }[];
}
const props = defineProps({
  processNode: {
    type: Object as PropType<ProcessNodeType>,
    required: true,
  }
});

const fontSizeList = ref<{ label: string; value: number }[]>([])
const formRef = ref()
// 动态生成验证规则
const rules = computed(() => {
  const rulesObj: any = {}

  props.processNode.processNodeConfigs.forEach((item, index) => {
    rulesObj[`processNodeConfigs.${index}.mainTitle`] = [
      {
        required: true,
        trigger: 'blur',
        message: $t('common.requiredTxt', [$t('certificate.settingProcessNode.mainTitle')])
      }
    ]
  })

  return rulesObj
})

const handlePlay = (item: any) => {
  item.isActive = !item.isActive
}
const handleDeleteAttribute = (config: any) => {
  props.processNode.processNodeConfigs = props.processNode.processNodeConfigs.filter((item: any) => item.id !== config.id)
}

const onDragEnd = (evt: any) => {
  console.log('拖拽完成:', evt)
}
const handleAddText = () => {
  props.processNode.processNodeConfigs.push({
    id: generateUUID(),
    icon: '',
    mainTitle: '',
    mainTextFormatConfigs: {
      fontSize: 12,
      fontColor: '#000000',
      fontBold: false,
      italic: false,
      underline: false,
    },
    subTitle: '',
    subTextFormatConfigs: {
      fontSize: 12,
      fontColor: '#000000',
      fontBold: false,
      italic: false,
      underline: false,
    },
    isActive: true,
  })
}

onMounted(() => {
  fontSizeList.value = Array.from({ length: 51 }, (_, index) => index + 10).map((item: number) => {
    return {
      label: `${item}px`,
      value: item
    }
  })
})

const emit = defineEmits(['update:modelValue', 'queryData']);

// 表单验证方法
const validateNode = async () => {
  try {
    await formRef.value?.validate()
    return true
  } catch (error) {
    return false
  }
}

// 暴露验证方法
defineExpose({
  validateNode
})

</script>
<template>
  <div class="w-full h-full overflow-scroll pr-[1px]">
    <el-form ref="formRef" :rules="rules" :model="processNode" class="w-full affix-node-container" label-position="top">
      <el-affix position="top" :offset="65" target=".affix-node-container">
        <div class="w-full bg-[#fff]">
          <el-button type="primary" @click="handleAddText" class="mb-[15px]">{{ $t('common.newTxt')
          }}</el-button>
        </div>
      </el-affix>
      <draggable 
        :list="props.processNode.processNodeConfigs" 
        :animation="150" 
        item-key="id" 
        class="w-full"
        handle=".drag-handle"
        @end="onDragEnd"
      >
        <template #item="{ element: item, index: idx }">
          <el-form-item class="w-full" :label="item.mainTitle" :key="item.id">
          <template #label>
            <div
              class="w-full flex items-center justify-between bg-[#F2F7FD] rounded-[4px] p-[5px] text-[#191919] font-[500]">
              <div @click="handlePlay(item)" class="cursor-pointer select-none">
                <Play fill="#595959" class="text-[#595959] play-icon scale-[0.6] inline-block align-top"
                  :class="{ 'play-icon-active': item.isActive }"></Play>
                <span>{{ item.mainTitle }}</span>
              </div>
              <div class="flex items-center">
                <el-tooltip effect="dark" :content="$t('common.deleteTxt')" :show-after="1000" placement="top">
                  <el-button link :icon="Trash2" @click="handleDeleteAttribute(item)" />
                </el-tooltip>
                <el-tooltip effect="dark" :content="$t('common.sortTxt')" :show-after="1000" placement="top">
                  <el-button link :icon="GripVertical" class="w-[16px] h-[16px] ml-[12px] drag-handle" />
                </el-tooltip>
                </div>
            </div>
          </template>
          <template #default>
            <div :class="{ 'hidden': !item.isActive }" class="w-full pt-[12px] transition-all duration-200">
              <div class="flex items-center mb-[20px]">
                <div class="w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                  $t('certificate.settingProcessNode.iconSetting') }}</div>
                <div class="flex-1 flex items-top">
                  <UploadIcon v-model:icon="item.icon" :border-radius="'50%'" />
                  <div class="text-[#AEAEAE] leading-[22px] text-[12px] ml-[12px]">{{
                    $t('certificate.supportFormat', { size: '48X48' }) }}</div>
                </div>
              </div>
              <div class="w-full mb-[20px]">
                <el-form-item label-width="72px" :label="$t('certificate.settingProcessNode.mainTitle')"
                  label-position="left" :prop="`processNodeConfigs.${idx}.mainTitle`" required>
                  <template #label>
                    <span class="leading-[34px] text-[14px] text-[#595959]">{{
                      $t('certificate.settingProcessNode.mainTitle') }}</span>
                  </template>
                  <template #default>
                    <div class="w-full">
                      <el-input class="w-full" type="text" maxlength="10" show-word-limit v-model="item.mainTitle"
                        :placeholder="$t('common.inputPhTxt', [$t('certificate.settingProcessNode.mainTitle')])" />
                    </div>
                  </template>
                </el-form-item>
              </div>
              <div class="flex items-center mb-[20px]">
                <div class="flex-none w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                  $t('certificate.settingBanner.textSetting') }}</div>
                <SetTextFormat class="flex-auto" v-if="item.isActive" v-model:modelValue="item.mainTextFormatConfigs" />
              </div>
              <div class="flex items-top mb-[20px]">
                <div class="w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                  $t('certificate.settingProcessNode.subTitle') }}</div>
                <el-input class="flex-1" type="textarea" maxlength="30" :rows="2" show-word-limit
                  v-model="item.subTitle"
                  :placeholder="$t('common.inputPhTxt', [$t('certificate.settingProcessNode.subTitle')])" />
              </div>
              <div class="flex items-center">
                <div class="flex-none w-[60px] mr-[12px] text-[#595959] text-[14px] leading-[22px] text-right">{{
                  $t('certificate.settingBanner.textSetting') }}</div>
                <SetTextFormat class="flex-auto" v-if="item.isActive" v-model:modelValue="item.subTextFormatConfigs" />
              </div>
            </div>
          </template>
        </el-form-item>
        </template>
      </draggable>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
:deep(.el-button+.el-button) {
  margin-left: 0;
}

.play-icon {
  cursor: pointer;
  transition: transform 0.2s;
}

.play-icon-active {
  transform: rotate(90deg) scale(0.6);
  transition: transform 0.2s;
}

.drag-handle {
  cursor: pointer;
  transition: all 0.2s ease;
}

</style>
